// 模态对话框，增加或者修改路由设置
"use client";

import { v4 as uuidv4 } from "uuid";
import { addRouter, updateRouter } from "../action/router";
import {
  RenderForm,
  RouterName,
  resetForm,
  checkRouter,
  checkName,
} from "./form";
import DriverSelect from "./driver";

// dialogName: 对话框名称，增加路由或者编辑路由
// router 就是当前选择的 router，在编辑的时候带入的数据
export default function RouterForm({
  dialogName,
  driverList,
  driverName,
  router,
  SetDriverName,
  refresh,
}) {
  const showError = () => {
    document.getElementsByName("router_alert")[0].classList.remove("hidden");
  };

  const handleSubmit = async (formData) => {
    const name = formData.get("name");

    // 检查驱动名称是否填写
    checkName(name);

    // 检查是否有同名路由
    if (dialogName === "增加路由") checkRouter(name);

    // 添加或者更新路由
    const result =
      dialogName === "增加路由"
        ? await addRouter(formData)
        : await updateRouter(router.id, formData);

    if (result.status === "error") {
      // 显示错误信息
      showError();
      return;
    }

    // 重置表单
    resetForm();

    // 刷新 table 页面，获取最新的驱动列表
    await refresh();
  };

  return (
    <div className="mx-auto w-full max-w-xl">
      <form
        className="card mb-4 rounded bg-white px-8 pb-8 pt-6 shadow-md"
        action={handleSubmit}
        id="router_form"
      >
        <span className="card-title mb-10 mt-2 gap-2">{dialogName}</span>
        <div className="grid grid-cols-6 gap-2">
          <div className="col-span-2">
            <DriverSelect
              driverList={driverList}
              SetDriverName={SetDriverName}
            />
          </div>
          <div key={uuidv4()} className="col-span-4 mb-4">
            <RouterName router={router} />
          </div>
        </div>
        <RenderForm driverName={driverName} router={router} />
        <div className="flex items-center justify-end gap-2">
          <button className="btn btn-wide" type="button" onClick={resetForm}>
            取消
          </button>

          <button className="btn btn-wide btn-neutral" type="submit">
            提交
          </button>
        </div>
      </form>
    </div>
  );
}
